<template>
  <div class="search_contanier">
    <!-- 搜索框 -->
    <form action="/">
      <!-- Tips: 在 van-search 外层增加 form 标签，且 action 不为空，即可在 iOS 输入法中显示搜索按钮。-->
      <van-search
        v-model="value"
        show-action
        background="#3296fa"
        placeholder="请输入搜索关键词"
        @search="onSearch(value)"
        @cancel="onCancel"
        action-text="返回"
        @focus="isResultShow = false"
      />
    </form>
    <!-- 搜索结果 -->
    <search-result v-if="isResultShow" :value="value"></search-result>
    <!-- 联想建议 -->
    <search-suggestion
      v-else-if="value"
      :value="value"
      @input="(val) => onSearch(val)"
    ></search-suggestion>
    <!-- 搜索历史记录 -->
    <search-history
      v-else
      :historySearch="historySearch"
      @input="(val) => onSearch(val)"
      @delAll="historySearch = []"
    ></search-history>
  </div>
</template>

<script>
// 注册组件
import SearchHistory from "./components/search-history.vue";
import SearchSuggestion from "./components/search-suggestion.vue";
import SearchResult from "./components/search-result.vue";
// 拿到本地存储的方法
import { setItem, getItem } from "@/utils/storage.js";
export default {
  data() {
    return {
      value: "",
      isResultShow: false, //控制搜索结果
      historySearch: getItem("TOUTIAO_HISTORY") || [], //搜索历史记录数组
    };
  },
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResult,
  },
  watch: {
    historySearch() {
      return setItem("TOUTIAO_HISTORY", this.historySearch);
    },
  },
  methods: {
    // 回车确认搜索执行函数
    onSearch(val) {
      // 将搜索关键词实时传给子组件搜索结果去叫他掉接口
      this.value = val;
      this.historySearch.unshift(val);
      this.historySearch = [...new Set(this.historySearch)];
      //确定搜索展示搜索结果
      this.isResultShow = true;
    },
    // 点击取消执行函数
    onCancel() {
      // 跳回上一级路由
      this.$router.back();
    },
  },
};
</script>

<style scoped lang="less">
.search_contanier {
  padding-top: 106px;
  .van-search__action {
    background-color: #3296fa;
    color: #fff;
  }
  .van-search {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1;
  }
  .van-search__action {
    color: #fff;
  }
}
</style>